﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using LifeMed.Data.Core.ContextFactory;

namespace LifeMed.Data.Core.Repository
{
    public abstract class Repository<T> where T : class
    {
        private DbContext _dataContext;
        private readonly IDbSet<T> _dbSet;

        protected Repository(IDbContextFactory dbContextFactory)
        {
             DbContextFactory = dbContextFactory;
            _dbSet = DataContext.Set<T>();
        }

        protected IDbContextFactory DbContextFactory
        {
            get;
            private set;
        }

        protected DbContext DataContext
        {
            get { return _dataContext ?? (_dataContext = DbContextFactory.Instance); }
        }

        public virtual void Add(T entity)
        {
            _dbSet.Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _dbSet.Remove(entity);
        }

        public virtual T GetById(long id)
        {
            return _dbSet.Find(id);
        }

        public virtual IEnumerable<T> GetAll()
        {
            return _dbSet.ToList();
        }
        public virtual IEnumerable<T> GetMany(Func<T, bool> where)
        {
            return _dbSet.Where(where).ToList();
        }
        public T Get(Func<T, Boolean> where)
        {
            return _dbSet.Where(where).FirstOrDefault<T>();
        }
    }
}